import { defineStore } from 'pinia'

export interface ArticleItem {
  id: number
  title: string
  author: string
  status: 'draft' | 'published'
  updatedAt: string
  views: number
}

const KEY = 'articles'

function load(): ArticleItem[] {
  const raw = localStorage.getItem(KEY)
  if (raw) return JSON.parse(raw)
  const seed: ArticleItem[] = Array.from({ length: 12 }).map((_, i) => ({
    id: i + 1,
    title: `文章标题 ${i + 1}`,
    author: i % 2 ? 'Admin' : 'Editor',
    status: Math.random() > 0.5 ? 'published' : 'draft',
    updatedAt: new Date(Date.now() - i * 86400000).toISOString(),
    views: Math.floor(Math.random() * 1000)
  }))
  localStorage.setItem(KEY, JSON.stringify(seed))
  return seed
}

export const useArticlesStore = defineStore('articles', {
  state: () => ({
    items: [] as ArticleItem[]
  }),
  actions: {
    hydrate() {
      this.items = load()
    },
    save() {
      localStorage.setItem(KEY, JSON.stringify(this.items))
    },
    list(params?: { keyword?: string; status?: 'draft' | 'published'; page?: number; pageSize?: number }) {
      const { keyword = '', status, page = 1, pageSize = 10 } = params || {}
      let data = [...this.items]
      if (keyword) data = data.filter(d => d.title.includes(keyword) || d.author.includes(keyword))
      if (status) data = data.filter(d => d.status === status)
      const total = data.length
      const start = (page - 1) * pageSize
      const pageData = data.slice(start, start + pageSize)
      return { items: pageData, total }
    },
    create(payload: Omit<ArticleItem, 'id' | 'updatedAt' | 'views'>) {
      const id = Math.max(0, ...this.items.map(i => i.id)) + 1
      const item: ArticleItem = { id, views: 0, updatedAt: new Date().toISOString(), ...payload }
      this.items.unshift(item)
      this.save()
      return item
    },
    update(id: number, patch: Partial<Omit<ArticleItem, 'id'>>) {
      const idx = this.items.findIndex(i => i.id === id)
      if (idx >= 0) {
        this.items[idx] = { ...this.items[idx], ...patch, updatedAt: new Date().toISOString() }
        this.save()
      }
    },
    remove(id: number) {
      this.items = this.items.filter(i => i.id !== id)
      this.save()
    },
    togglePublish(id: number) {
      const item = this.items.find(i => i.id === id)
      if (item) {
        item.status = item.status === 'published' ? 'draft' : 'published'
        item.updatedAt = new Date().toISOString()
        this.save()
      }
    }
  }
})


